import API from "@/api";
import request from "../../utils/js/request";
import {
  setToken,
  removeToken,
  setStorage,
  getStorage,
  getToken,
  getRefreshToken,
} from "@/utils/service/auth";
import router, { resetRouter } from "@/router";
import _ from "lodash";

const getDefaultState = () => {
  return {
    name: "",
    userInfo: {},
    roles: null, // null 》代表用户未登录，[] 》已登录但权限列表为空
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { login_name, password } = userInfo;
    return new Promise((resolve, reject) => {
      API.login({ login_name: login_name.trim(), password: password })
        .then(({ data }) => {
          setToken(
            `Bearer ${data.access_token}`,
            `Bearer ${data.refresh_token}`
          );
          let userInfo = _.omit(data, ["access_token", "refresh_token"]);
          commit("SET_USERINFO", userInfo);
          console.log(userInfo)
          setStorage("userInfo", userInfo);
          setStorage("roles", userInfo.roles);
          API.getAdminResource().then(({data})=>{
            let rolesId=data.map(item=>{
              return item.id
            })
            setStorage("rolesId", rolesId);
          })

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  phoneLogin({ commit }, userInfo){
    console.log(userInfo)
    const { phone, code } = userInfo;

    return new Promise((resolve, reject) => {
      API.phoneLogo({ phone: phone, code: code })
        .then(({ data }) => {
          console.log(data)
          setToken(
            `Bearer ${data.access_token}`,
            `Bearer ${data.refresh_token}`
          );
          let userInfo = _.omit(data, ["access_token", "refresh_token"]);
          commit("SET_USERINFO", userInfo);
          console.log(userInfo)
          setStorage("userInfo", userInfo);
          setStorage("roles", userInfo.roles);
          API.getAdminResource().then(({data})=>{
            let rolesId=data.map(item=>{
              return item.id
            })
            setStorage("rolesId", rolesId);
          })

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // API.getUserInfo()
      //   .then(({ data }) => {
      let permission = getStorage("roles");
      commit("SET_ROLES", permission);
      resolve();
      // })
      // .catch((err) => {
      //   reject(err);
      // });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken(); // must remove  token  first
      resetRouter();
      commit("RESET_STATE");
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },

  changeToken({ commit }) {
    return new Promise((resolve, reject) => {
      let refresh_token = getRefreshToken();
      setToken(refresh_token);
      console.log("来");
      API.getRefreshToken()
        .then(({ data }) => {
          console.log(data);
          setToken(data.access_token, data.refresh_token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
      //
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
